package com.woniu.tmsauth.service.impl;

import com.woniu.tmsauth.service.mapper.MenuMapper;
import com.woniu.tmsauth.service.MenuService;
import com.woniu.tmscommons.entity.Menu;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Service
public class MenuServiceImpl implements MenuService {
    @Resource
    private MenuMapper menuMapper;

    @Override
    public List<Menu> queryMenusByUid(Integer id) {
        // 查询当前用户角色的所有菜单
        List<Menu> allMenus = menuMapper.queryMenusByUid(id);
        List<Menu> menusTree = new ArrayList<>();
        // 用于存储每个菜单项的子菜单
        Map<Integer, Menu> menuMap = new HashMap<>();

        // 将所有菜单项按ID存储到Map中
        for (Menu menu : allMenus) {
            menuMap.put(menu.getId(), menu);
        }
        log.debug("Menu map contents: {}", menuMap);
        // 构建树形结构
        for (Menu menu : allMenus) {
            if (menu.getPid() == 0) {
                menusTree.add(menu);
            } else {
                Menu parentMenu = menuMap.get(menu.getPid());
                if (parentMenu != null) {
                    if (parentMenu.getChildren() == null) {
                        parentMenu.setChildren(new ArrayList<>());
                    }
                    parentMenu.getChildren().add(menu);
                }
            }
        }
        // 动态生成每个菜单的面包屑
        generateBreadcrumbs(menusTree, new ArrayList<>());

        return menusTree;
    }
    private void generateBreadcrumbs(List<Menu> menus, List<String> currentPath) {
        for (Menu menu : menus) {
            // 复制当前路径并添加当前菜单名
            List<String> breadcrumb = new ArrayList<>(currentPath);
            breadcrumb.add(menu.getName());
            menu.setBreadcrumb(breadcrumb);

            // 如果有子菜单，递归处理
            if (menu.getChildren() != null) {
                generateBreadcrumbs(menu.getChildren(), breadcrumb);
            }
        }
    }
}
